'use strict';
import React, {
    Component
} from 'react'
import {
    Link,
    hashHistory
} from 'react-router'
import {
    HttpService,
    Toast,
    imgonError
} from '../Http'
import Header from './common/Header'


import imgHead from '../img/icon/head.png'
import defaultHeadImg from '../img/icon/defaultHeadImg.png'
import imgClean from '../img/icon/clean.png'

import imgLbs from '../img/icon/lbs.png'
import imgGps from '../img/icon/gps.png'
import imgWifi from '../img/icon/wifi.png'

import dian from '../img/icon/dianHead.png'

import imgDian0 from '../img/icon/dianliang0.png'
import imgDian1 from '../img/icon/dianliang1.png'
import imgDian2 from '../img/icon/dianliang2.png'
import imgDian3 from '../img/icon/dianliang3.png'
import imgDian4 from '../img/icon/dianliang4.png'

export default class Map extends Component {
    constructor(props) {
        super(props);
        this.babyid = this.props.params.babyid;
        this.babyname = this.props.params.babyname;
        this.headimg = this.props.params.headimg;
        this.map = '';
        this.marker = '';
        this.state = {
            babyInfo: {
                powerValue: imgDian0, //电量
                datasource: '', //基站类型
                address: '当前设备未定位',
                time: new Date().getHours() + ':' + new Date().getMinutes(), //默认当前时间的小时.分钟
                lat: '39.90923',
                lng: '116.397428'
            }, //学生信息
            locaType: false, //定为动画
            timeposi: false
        };
    }
    componentWillMount() {
        //获取当前学生的定位信息
        this.getCurrentTrack();
    }

    /**
     *  获取定位信息
     */
    getCurrentTrack() {
        HttpService.query({
            url: '/app/map/getCurrentTrack',
            data: {
                token: localStorage.appToken,
                babyid: this.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                console.log(res);
                if (res.code == 10059) {
                    this.init(116.397428, 39.90923);
                    Toast.toast('未获取到定位信息');
                } else if (res.code == 10060) {
                    let datasource = imgLbs,
                        time = res.data.gpstime,
                        rct = this,
                        timeposi = false
                    this.init(res.data.lng, res.data.lat);
                    if (res.data.powerValue == 1) {
                        datasource = imgGps;
                    } else if (res.data.datasource == 2) {
                        datasource = imgWifi;
                    }
                    if (res.data.gpstime) {
                        let gpstime = res.data.gpstime.replace(/\-/g, '/')
                        let timediff = new Date().getTime() - new Date(gpstime).getTime()
                        if (timediff / 1000 / 60 / 10 > 1) {
                            timeposi = true
                        }
                        if (new Date().getFullYear() == new Date(gpstime).getFullYear())
                            gpstime = gpstime.substr(5)
                        time = gpstime.slice(0, -3).replace(/\//g, '.')
                    }
                    let geocoder = new AMap.Geocoder({
                        radius: 1000,
                        extensions: "all"
                    });
                    geocoder.getAddress([res.data.lng, res.data.lat], function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            let babyInfo = rct.state.babyInfo;
                            babyInfo.address = result.regeocode.formattedAddress;
                            rct.setState({
                                babyInfo
                            });
                        }
                    });
                    if (!this.state.locaType) {
                        this.getCurrentPower(); //获取电量
                    }
                    let babyInfo = this.state.babyInfo;
                    babyInfo.datasource = datasource;
                    babyInfo.time = time;
                    babyInfo.lat = res.data.lat;
                    babyInfo.lng = res.data.lng;
                    this.setState({
                        babyInfo,
                        locaType: false,
                        timeposi
                    });
                    // let getTime = new Date(res.data.gpstime.split(' ')[0]);
                    // let nowTime = new Date();
                    // let Toast.toast = getTime.getFullYear() == nowTime.getFullYear() && getTime.getMonth() == nowTime.getMonth() && nowTime.getDate() == getTime.getDate();
                    // if (!Toast.toast)
                    //     Toast.toast('无法获取当前定位<br/>将显示上次定位信息')
                } else {
                    Toast.toast(res.data.msg);
                    this.setState({
                        locaType: false
                    });
                }
            })
        });
    }
    /**
     * 获取电量
     */
    getCurrentPower() {
        HttpService.query({
            url: '/app/alarm/getCurrentPower',
            sync: false,
            data: {
                token: localStorage.appToken,
                babyid: this.babyid,
                weixinclient: 'true'
            },
            success: (res => {
                console.log(res);
                if (res.code == 10011) {
                    Toast.toast('未获取到学生证电量信息<br/>请检查电量、或是否开机');
                } else {
                    let powerValue = imgDian1;
                    if (res.data.powerValue == 2) {
                        powerValue = imgDian2;
                    } else if (res.data.powerValue == 3) {
                        powerValue = imgDian3;
                    } else if (res.data.powerValue == 4) {
                        powerValue = imgDian4;
                    }
                    this.state.babyInfo.powerValue = powerValue;
                    this.setState({
                        babyInfo: this.state.babyInfo
                    });
                }
            })
        })
    }

    /**
     * 地图初始化
     * @param lng 纬度
     * @param lat 经度
     */
    init(lng, lat) {
        let rct = this;
        if (!rct.state.locaType) {
            rct.map = new AMap.Map('container', {
                zoom: 15,
                center: [
                    lng, lat
                ],
                resizeEnable: true
            });
        } else {
            rct.map.clearMap(); //清除所有覆盖物
            rct.map.setZoomAndCenter(15, [lng, lat]); //重新定位的时候直接定位中心点
        }
        rct.map.plugin(["AMap.ToolBar"], function() {
            let tool = new AMap.ToolBar({
                position: 'RT'
            });
            rct.map.addControl(tool);
        });
        if (lng == 116.397428 && lat == 39.90923) {
            return;
        }

        rct.marker = new AMap.Marker({
            map: rct.map,
            position: [lng, lat],
            content: '<img src=' + dian + ' class="headBgImg" />',

        });
        rct.marker.setMap(rct.map);
        if (rct.headimg == '/media')
            rct.headimg = defaultHeadImg;
        rct.marker = new AMap.Marker({
            map: rct.map,
            position: [lng, lat],
            content: `<img src=${this.headimg} class="headImg" />`,
        });
        rct.marker.setMap(rct.map);

        let circle = new AMap.Circle({
            center: new AMap.LngLat(lng, lat), // 圆心位置
            radius: 100, //半径
            strokeColor: "#00b4ed", //线颜色
            strokeOpacity: 1, //线透明度
            fillColor: "#00b4ed", //填充颜色
            strokeWeight: 1, //线宽
            fillOpacity: 0.2 //填充透明度
        });
        circle.setMap(rct.map);
    }

    /**
     * 点击定位
     * @returns {XML}
     */
    location() {
        if (!this.state.locaType) {
            this.setState({
                locaType: true
            });
            this.getCurrentTrack(); //重新获取定为信息
        }
    }

    /**
     * 返回到列表页面
     * @returns {XML}
     */
    goBack() {
        hashHistory.goBack(-1);
    }
    /**
     * 显示默认图片
     * @param e
     */
    mapImgonError() {
        let rct = this;
        document.querySelector('.h_back').src = defaultHeadImg;
        if (document.querySelector('.headImg')) {
            document.querySelector('.headImg').src = defaultHeadImg;
        } else {
            setTimeout(function() {
                rct.mapImgonError();
            }, 200);
        }
    }
    render() {
        const {
            timeposi,
            babyInfo
        } = this.state
        return (
            <div className='pjbmap'>
                <Header back={<img className='h_back' src={this.headimg} onError={this.mapImgonError.bind(this)} />} link={<img onClick={this.goBack.bind(this)} className='h_link' src={imgClean}/>}>
                    <div className='info'>
                        <div className="title">
                            <span className="name">{this.babyname}</span>
                            <span className="position">&nbsp;&nbsp;{timeposi == true?<b className='timeposi'>设备定位未更新</b>:'设备当前定位'}</span>
                            <img src={babyInfo.powerValue}/>
                            {
                                babyInfo.datasource!=''?<img src={babyInfo.datasource} />:''
                            }
                        </div>
                        <div className="content">
                            <span className="time">{timeposi == true?'定位时间：':null}{babyInfo.time}</span>
                            <span className="address">{babyInfo.address}</span>
                        </div>
                    </div>
                </Header>
                <div className="location" onClick={this.location.bind(this)}>
                    {this.state.locaType==false?'':<div className="locationLoading"/>}
                    <div className={this.state.locaType==false?'locationBg':'locationBg ing'}/>
                </div>
                <div id="container"></div>
            </div>
        )
    }
}
